package com.nuoniu.sibanyun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.common.lang.StringUtils;
import com.nuoniu.sibanyun.entity.SysRole;
import com.nuoniu.sibanyun.entity.SysRoleDataScope;
import com.nuoniu.sibanyun.entity.SysRoleMenu;
import com.nuoniu.sibanyun.entity.SysUserRole;
import com.nuoniu.sibanyun.entity.dto.SysRoleDto;
import com.nuoniu.sibanyun.mapper.SysRoleMapper;
import com.nuoniu.sibanyun.mapper.SysUserRoleMapper;
import com.nuoniu.sibanyun.service.ISysRoleDataScopeService;
import com.nuoniu.sibanyun.service.ISysRoleMenuService;
import com.nuoniu.sibanyun.service.ISysRoleService;
import com.nuoniu.sibanyun.service.ISysUserRoleService;
import com.nuoniu.sibanyun.service.crm.ICrmGoodsService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author baiqiang
 * @since 2020-04-23
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

    @Autowired
    private ISysRoleMenuService sysRoleMenuService;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private ISysRoleDataScopeService sysRoleDataScopeService;
    @Autowired
    private SysUserRoleMapper userRoleMapper;
    @Autowired
    private ISysUserRoleService userRoleService;
    @Autowired
    private ICrmGoodsService goodsService;

    @Override
    public List<SysRole> listByUserId(Long userId) {
        List<SysRole> sysRoles = baseMapper.listByUserId(userId);
        return sysRoles;
    }

    @Override
    public List<SysRole> listByMenuId(Long menuId) {
        UserInfo userInfo = UserThreadLocal.get();
        List<SysRole> sysRoles = baseMapper.listByMenuId(menuId);
        return sysRoles;
    }

    @Override
    public Page<SysRole> getRolePage(SysRoleDto sysRoleDto) {
        UserInfo userInfo = UserThreadLocal.get();
        SysRole sysRole = new SysRole();
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>(sysRole);
        if(StringUtils.isNotBlank(sysRoleDto.getRoleName())) {
            queryWrapper.like("role_name", sysRoleDto.getRoleName());
        }
        if(sysRoleDto.getStatus() != null) {
            queryWrapper.eq("status", sysRoleDto.getStatus());
        }

        queryWrapper.eq("company_id", userInfo.getCompanyId());
        queryWrapper.orderByAsc("role_sort");
        Page page = page(sysRoleDto.getPage(), queryWrapper);
        return page;
    }

    @Override
    public void deleteRole(Long id) {
        List<SysUserRole> userRoleList = userRoleService.getByRoleId(id);
        if(userRoleList.size() > 0) {
            throw new NuoNiuException("角色正在使用，不能删除");
        }

        Integer count =  goodsService.getCountByRoleId(id);
        if(count != null && count > 0) {
            throw new NuoNiuException("角色正在使用,不能删除");
        }

        sysRoleMenuService.removeById(id);
        sysRoleDataScopeService.removeById(id);
        userRoleMapper.deleteByRole(id);
        removeById(id);
    }

    @Override
    public void saveRole(SysRoleDto sysRoleDto) {
        UserInfo userInfo = UserThreadLocal.get();
        SysRole sysRole = new SysRole();
        BeanUtils.copyProperties(sysRoleDto, sysRole);
        sysRole.setCompanyId(userInfo.getCompanyId());
        sysRole.setCompanyName(userInfo.getCompanyName());
        if(sysRole.getId() == null) {
            //是否系统角色
            if(userInfo.getUserId().equals(1)) {
                sysRole.setIsSys(true);
            }

            sysRole.setCreateBy(userInfo.getUserId());
            sysRoleMapper.insert(sysRole);
        }else {
            sysRole.setUpdateBy(userInfo.getUserId());
            sysRole.setStatus(sysRoleDto.getStatus());
            baseMapper.updateById(sysRole);
        }

        //菜单授权
        if(StringUtils.isNotBlank(sysRoleDto.getRoleName())) {
            sysRoleMenuService.removeById(sysRole.getId());
            List<SysRoleMenu> roleMenus = new ArrayList<>();
            for (int i=0; i<sysRoleDto.getMenuId().size(); i++) {
                SysRoleMenu sysRoleMenu = new SysRoleMenu();
                sysRoleMenu.setRoleId(sysRole.getId());
                sysRoleMenu.setMenuId(sysRoleDto.getMenuId().get(i));
                roleMenus.add(sysRoleMenu);
            }
            sysRoleMenuService.saveBatch(roleMenus);
        }

        //自定义机构数据范围
        sysRoleDataScopeService.removeById(sysRole.getId());
        if(StringUtils.isNotBlank(sysRoleDto.getRoleName()) && sysRole.getDataScope() == 4) {
            List<SysRoleDataScope> sysRoleDataScopes = new ArrayList<>();
            for (int i=0; i<sysRoleDto.getOfficeId().size(); i++) {
                SysRoleDataScope sysRoleDataScope = new SysRoleDataScope();
                sysRoleDataScope.setRoleId(sysRole.getId());
                sysRoleDataScope.setCtrlType("office");
                sysRoleDataScope.setCtrlData(sysRoleDto.getOfficeId().get(i));
                sysRoleDataScope.setCtrlPermi("1");
                sysRoleDataScopes.add(sysRoleDataScope);
            }
            sysRoleDataScopeService.saveBatch(sysRoleDataScopes);
        }

        //自定义用户数据范围
        if(StringUtils.isNotBlank(sysRoleDto.getRoleName()) && sysRole.getDataScope() == 5) {
            List<SysRoleDataScope> roleDataScopes = new ArrayList<>();
            for (int i=0; i<sysRoleDto.getUserId().size(); i++) {
                String id = sysRoleDto.getUserId().get(i);
                if(!id.contains("user")) {
                    continue;
                }

                SysRoleDataScope sysRoleDataScope = new SysRoleDataScope();
                sysRoleDataScope.setRoleId(sysRole.getId());
                sysRoleDataScope.setCtrlType("user");
                sysRoleDataScope.setCtrlData(Long.parseLong(id.split("_")[0]));
                sysRoleDataScope.setCtrlPermi("1");
                roleDataScopes.add(sysRoleDataScope);
            }
            sysRoleDataScopeService.saveBatch(roleDataScopes);
        }
    }

    @Override
    public List<SysRoleDto> getRoleAll() {
        UserInfo userInfo = UserThreadLocal.get();
        return sysRoleMapper.getRoleAll(userInfo.getCompanyId());
    }
}
